var colors = require('colors');

var of = require('hy5b/backend/write');

var fs = require('fs'),
    path = require('path'),
    argv = process.argv;


var directory = argv[2];
var fileList = [];

fs.readdir(directory, function(err, files) {

    if (!files.length) {
        return console.log('No files to show!'.red);
    }

    function file(i) {

        var filename = path.resolve(directory, files[i]);


        fs.stat(filename, function(err, stat) {

            if (stat.isFile())
            {
                fileList.push(filename);
            }

            i++;

            if (i == files.length) {
                read();
            } else {
                file(i);
            }
        });
    }

    function read() {
        for (var i = 0; i < fileList.length; i++)
        {
            (function(i) {
                var fileName = fileList[i];
                fs.readFile(fileName, 'utf8', function(err, data) {
                    findJavaOutline(data, fileName);
                });
            }(i));
        }
    }

    function findJavaOutline(content, fileName) {
        var pattern = /((public|protected|private) *[\w<>, \[\]]+ *\w+ *\( *(@\w+ *)?\S+ *\S+ *[\r\n]*( *, *[\r\n]* *(@\w+ *)?\S+ *\S+ *)* *\)) *([\r\n]* *throws *\w+ *( *, *[\r\n]* *\w+)*)? *\{/g;

        var matches = pattern.exec(content);
        
        while (matches)
        {
            var signature = matches[1].replace(/[\r\n]+/g, " ").replace(/ {2,}/g, " ");
            judgeFunction(signature, fileName);
            matches = pattern.exec(content);
        }

    }

    var ofSuccess = of("success.log");

    var ofFail = of("fail.log")

    var patterns = [
            /add[^\(]*\( *(@\w+ *)?\w+ *\w+ *, *BindingResult *\w+ *, *HttpServletRequest *\w+ *\)/,
            /modify[^\(]*\( *(@\w+ *)?\w+ *\w+ *, *BindingResult *\w+ *, *HttpServletRequest *\w+ *\)/,
            /delete[^\(]*\( *String\[\] *\w+ *, *HttpServletRequest *\w+ *, *\w+ *\w+ *, *BindingResult *\w+ *\)/,
            /query[^\(]*\([^\)]*\)/,
            /show[^\(]*\([^\)]*\)/
        ],
        color = ["bgRed", "bgGreen", "bgBlue", 'bgCyan', 'bgCyan'];

    function judgeFunction(signature, fileName) {
        var matched = false;
        for (var i = 0; i < patterns.length; i++)
        {
            if (patterns[i].test(signature))
            {
                console.log(path.basename(fileName).yellow);
                console.log(signature[color[i]]);
                ofSuccess.write(path.basename(fileName) + ' ' + signature + '\r\n');
                matched = true;
                break;
            }
        }

        if (!matched)
        {
            console.log(path.basename(fileName).yellow);
            console.log(signature);
            ofFail.write(path.basename(fileName) + ' ' + signature + '\r\n');
        }
    }

    file(0);
});